<?php

namespace App\Library\Message\Channels;

use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class SmsChannel implements ShouldQueue
{
    private $client;

    public function __construct()
    {
        $config = [
            'accessKeyId' => config('aliyun.access_key_id'),
            'accessKeySecret' => config('aliyun.access_key_secret'),
        ];

        $this->client = new Client($config);
    }

    public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor('sms', $notification)) {
            return;
        }

        $smsData = $notification->toSms($notifiable);

        if (is_null($smsData)) {
            return;
        }

        switch ($to['area_code']) {
            case '86':
                $region = 'mainland';
                break;
            default:
                $region = 'other';
        }

        $sign = config("aliyun.sms.sign.{$region}.{$smsData['sign']}");
        $template = config("aliyun.sms.template.{$region}.{$smsData['template']}");

        if (is_null($sign) || is_null($template)) {
            return;
        }

        $message = new SendSms();
        $message->setPhoneNumbers('00' . $to['area_code'] . $to['mobile']);
        $message->setSignName($sign);
        $message->setTemplateCode($template);
        $message->setTemplateParam($smsData['param']);

        $result = $this->client->execute($message);

        if (method_exists($notification, 'onSendFinished')) {
            $notification->onSendFinished('sms', $result);
        }
    }
}
